<template>
  <div class="deductTax">
    <div class="title">
      <h3>抵扣金</h3>
    </div>
    <el-row v-if="summaryData" :gutter="20">
      <el-col :span="8">
        <div class="ibox" @click="deductTaxTable">
          <div class="ibox-info">
            <div class="ibox-title">可用抵扣金</div>
            <div class="ibox-desc">{{ summaryData.couldUseTotal }}</div>
          </div>
          <i class="el-icon-arrow-right ibox-icon" />
        </div>
      </el-col>
      <el-col :span="8">
        <div class="ibox" @click="deductTaxTable">
          <div class="ibox-info">
            <div class="ibox-title">累计发放抵扣金</div>
            <div class="ibox-desc">{{ summaryData.cumulativeDisTotal }}</div>
          </div>
          <i class="el-icon-arrow-right ibox-icon" />
        </div>
      </el-col>
      <el-col :span="8">
        <div class="ibox" @click="deductTaxTable">
          <div class="ibox-info">
            <div class="ibox-title">累计消耗抵扣金</div>
            <div class="ibox-desc">{{ summaryData.cumulativeUseTotal }}</div>
          </div>
          <i class="el-icon-arrow-right ibox-icon" />
        </div>
      </el-col>
    </el-row>
    <div class="key-search">
      <el-form ref="form" :model="BindForm" label-width="80px" label-position="left">
        <el-form-item prop="name" label="规则名称:">
          <el-col :span="24">
            <el-input v-model="BindForm.name" placeholder="请输入规则名称" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item prop="state" label="规则状态:">
          <el-col :span="24">
            <el-radio-group v-model="BindForm.state" @change="reloadTableData">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="0">上线</el-radio-button>
              <el-radio-button label="1">下线</el-radio-button>
              <el-radio-button label="2">已结束</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="key-type">
      <el-radio-group v-model="BindForm.type" @change="reloadTableData">
        <el-radio-button label="0">发放规则</el-radio-button>
        <el-radio-button label="1">消耗规则</el-radio-button>
      </el-radio-group>
      <el-button
        type="primary"
        @click="addActive"
      >新增抵扣金规则</el-button>
    </div>
    <div class="ele-table">
      <el-table :data="BindTable" border max-height="600" :empty-text="loading ? '数据加载中' : (isSearch ? (BindForm.type == '0' ? '未找到相关的发放规则' : '未找到相关的消耗规则') : (BindForm.type == '0' ? '暂无发放规则': '暂无消耗规则'))" @selection-change="handleSelectionChange">
        <el-table-column :selectable="selectable" type="selection" fixed="left" width="40" :resizable="false" />
        <el-table-column
          label="规则名称"
          prop="name"
          align="center"
          min-width="200"
          :resizable="false"
          fixed="left"
        />
        <el-table-column
          label="规则类型"
          prop="type"
          align="center"
          width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type == 0" type="primary" size="small">发放规则</el-tag>
            <el-tag v-else type="primary" size="small">消耗规则</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="BindForm.type == '0'"
          label="发放方式"
          prop="ruleMethod"
          align="center"
          width="160"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.ruleMethod == 0">百分比（{{ scope.row.ruleValue }}%）</span>
            <span v-else>固定金额（{{ scope.row.ruleValue }}元）</span>
          </template>
        </el-table-column>
        <el-table-column
          v-else
          label="消耗方式"
          prop="ruleMethod"
          align="center"
          width="160"
          :resizable="false"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.ruleMethod == 0">百分比（{{ scope.row.ruleValue }}%）</span>
            <span v-else>固定金额（{{ scope.row.ruleValue }}元）</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="BindForm.type == '0'"
          label="已发放抵扣金"
          prop="money"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          v-else
          label="已消耗抵扣金"
          prop="money"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="开始时间"
          prop="startTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="结束时间"
          prop="endTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="规则状态"
          prop="state"
          align="center"
          width="120"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state == 2" type="info" size="small">已结束</el-tag>
            <el-tag v-else-if="scope.row.state == 1" type="info" size="small">下线</el-tag>
            <el-tag v-else-if="scope.row.state == 0" type="success" size="small">上线</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="上线时间"
          prop="onlineTime"
          align="center"
          width="160"
          :resizable="false"
        />
        <el-table-column
          label="操作"
          header-align="center"
          align="left"
          fixed="right"
          width="220"
          :resizable="false"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row.state == 0" type="text" @click="lowRow([scope.row])">下线</el-button>
            <el-button v-else-if="scope.row.state == 1" type="text" @click="upRow([scope.row])">上线</el-button>
            <el-button type="text" @click="$router.push({name:'deductTaxTable', query: { p: $ed(scope.row) }})">查看统计</el-button>
            <el-button v-if="scope.row.state == 1" type="text" @click="$router.push({name:'editDeductTax', query: { p: $ed(scope.row) }})">编辑</el-button>
            <el-button type="text" @click="deleteRow([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <div>
        <div v-if="selectedList && selectedList.length > 0" style="display: inline-flex;">
          <el-button size="mini" type="info" @click="lowRow(selectedList)">下线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="success" @click="upRow(selectedList)">上线（{{ selectedList.length }}）</el-button>
          <el-button size="mini" type="danger" @click="deleteRow(selectedList)">删除（{{ selectedList.length }}）</el-button>
        </div>
      </div>
      <el-pagination
        background
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="limit"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="pageSizeChange"
        @current-change="currentPageChange"
      />
    </div>
  </div>
</template>

<script>
import { ruleList, changeRuleState, deleteRule, summary } from '@/api/market'
import { Loading } from 'element-ui'
export default {
  name: 'DeductTax',
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      loading: false,
      isSearch: false,
      summaryData: null,
      BindForm: {
        name: null,
        type: '0',
        state: 'all'
      },
      BindTable: [],
      selectedList: []
    }
  },
  created() {
    const vm = this
    vm.loadTableData()
    vm.loadSummary()
  },
  methods: {
    loadSummary() {
      const vm = this
      summary().then(res => {
        vm.summaryData = res.data.data ? res.data.data : null
      }).catch(res => {
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    resetForm() {
      const vm = this
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    search() {
      const vm = this

      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.reloadTableData()
        }
      })
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.reloadTableData()
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.loadTableData()
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    selectable(row, index) {
      if (row['state'] === 0 || row['state'] === 1) {
        return true
      }
      return false
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = {
        page: vm.page,
        limit: vm.limit
      }

      if (vm.BindForm.name && vm.BindForm.name.length > 0) {
        data['name'] = vm.BindForm.name
        vm.isSearch = true
      }

      data['type'] = parseInt(vm.BindForm.type)

      if (vm.BindForm.state !== 'all') {
        data['state'] = parseInt(vm.BindForm.state)
        vm.isSearch = true
      }

      vm.loading = true
      ruleList(data).then(res => {
        vm.loading = false
        vm.total = res.data.data.total
        vm.BindTable = res.data.data.data ? res.data.data.data : []
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    deleteRow(list) {
      const vm = this

      let msg = '确定删除【' + list[0]['name'] + '】抵扣金活动规则吗？'
      if (list.length > 1) {
        msg = '确定批量删除选中的【' + list.length + '】个抵扣金活动规则吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        deleteRule({
          idList: vm.$XEUtils.pluck(list, 'id')
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('删除抵扣金活动规则成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    lowRow(list) {
      const vm = this

      let msg = '确定下线【' + list[0]['name'] + '】抵扣金活动规则吗？'
      if (list.length > 1) {
        msg = '确定批量下线选中的【' + list.length + '】个抵扣金活动规则吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changeRuleState({
          idList: vm.$XEUtils.pluck(list, 'id'),
          type: 1
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('下线抵扣金活动规则成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    upRow(list) {
      const vm = this

      let msg = '确定上线【' + list[0]['name'] + '】抵扣金活动规则吗？'
      if (list.length > 1) {
        msg = '确定批量上线选中的【' + list.length + '】个抵扣金活动规则吗？'
      }

      vm.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loadingInstance = Loading.service()
        changeRuleState({
          idList: vm.$XEUtils.pluck(list, 'id'),
          type: 0
        }).then(res => {
          loadingInstance.close()
          vm.$message.success('上线抵扣金活动规则成功')
          vm.reloadTableData()
        }).catch(res => {
          loadingInstance.close()
          if (res && res.data && res.data.errno !== 0) {
            vm.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
          }
        })
      }).catch(() => {})
    },
    /* 新增抵扣金规则*/
    addActive() {
      this.$router.push('addDeductTax')
    },
    /* 抵扣金统计*/
    deductTaxTable() {
      this.$router.push('deductTaxTable')
    }
  }
}
</script>

<style lang="scss" scoped>
.deductTax{
  padding: 30px;

  .ibox {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 10px;
    .ibox-info {
     .ibox-title {
      font-size: 18px;
     }
      .ibox-desc {
        margin-top: 10px;
        font-size: 24px;
        font-weight: bold;
      }
    }
    .ibox-icon {
      font-size: 24px;
    }
  }

  .ibox:active {
    background: #f1f1f1;
  }

  .key-search {
    margin-top: 30px;
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eeeeee;
    .cus-input {
      max-width: 400px;
    }
  }

  .key-type {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
  }
  .ele-table,
  .pagination {
    margin-bottom: 30px;
  }
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

}
</style>
